use model_graph_types::{
    connector::{Connector, ExecuteOptions, QueryOptions},
    database::{DataSource, DatabaseType},
    modeling::Value,
    transform::{DataTransformOptions, DataTransformSqlUnit, DataTransformUnit},
};

use sqlite_connector::SqliteConnector;

/// 根据数据库获取到元数据
pub async fn transform(
    source: &DataSource,
    target: &DataSource,
    unit: &DataTransformSqlUnit,
    options: &DataTransformOptions,
) -> anyhow::Result<()> {
    //连接数据库
    let source_connector = SqliteConnector::open(&source).await?;
    let target_connector = SqliteConnector::open(&target).await?;

    let query_sql = &unit.query;
    let insert_sql = &unit.insert;

    let ignore = options.ignore_errs;
    //
    let (_, result_values) = source_connector
        .query(query_sql, &vec![], QueryOptions {})
        .await?;

    for value in result_values {
        match value {
            Value::Array(cols) => {
                let result = target_connector
                    .execute(insert_sql, &cols, ExecuteOptions::default())
                    .await;
                if !ignore {
                    if let Err(err) = result {
                        tracing::error!("transform:{}", err);
                        return Err(err);
                    }
                }
            }
            _ => {
                tracing::debug!("==");
            }
        }
    }
    Ok(())
}
